package com.unswift.cloud.queue;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;
import com.unswift.cloud.utils.BeanUtils;
import com.unswift.utils.ObjectUtils;
import com.unswift.utils.ThreadUtils;

import jakarta.annotation.PostConstruct;

@Component
@Api(value="队列任务，内存队列任务，类似与Rabbit Mq，只是在内存执行，服务器关闭，队列任务会消失", author = "unswift", date = "2023-09-08", version = "1.0.0")
@SuppressWarnings({"unchecked", "rawtypes"})
public class LocalSecurityQueue {
	
	@ApiField("日志对象")
	protected final Logger logger=LoggerFactory.getLogger(this.getClass());

	@ApiField("任务队列")
	private LinkedBlockingQueue<QueueTask> taskQueue=new LinkedBlockingQueue<QueueTask>();
	
	@ApiField("延迟任务队列")
	private DelayQueue<DelayQueueTask> delayTaskQueue=new DelayQueue<DelayQueueTask>();
	
	@ApiField("是否有任务，如果被设置true，则表示有任务")
	private boolean haveTask=false;
	
	@PostConstruct
	@ApiMethod("初始化方法")
	public void init() {
		ThreadUtils.execute(new Runnable() {
			public void run() {
				while(true) {
					try {
						QueueTask task=taskQueue.take();
						if(ObjectUtils.isNotEmpty(task) && ObjectUtils.isNotEmpty(task.getTaskBean())) {
							try {
								BeanUtils.getBean(task.getTaskBean().getClass()).handle(task.getTaskData());
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						Thread.sleep(0);
					} catch (Exception e) {
						e.printStackTrace();
						logger.error(e.getMessage(), e);
					}
				}
			}
		});
		ThreadUtils.execute(new Runnable() {
			public void run() {
				while(true) {
					try {
						QueueTask task=delayTaskQueue.take();
						if(ObjectUtils.isNotEmpty(task) && ObjectUtils.isNotEmpty(task.getTaskBean())) {
							try {
								BeanUtils.getBean(task.getTaskBean().getClass()).handle(task.getTaskData());
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						Thread.sleep(0);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
	}
	
	public void offer(QueueTask task) {
		taskQueue.offer(task);
	}
	
	public void offerDelay(DelayQueueTask task) {
		delayTaskQueue.offer(task);
	}
}
